<?php

namespace App\Jobs\Zhunya;

use App\Models\CacheModel\AwardGoods;
use App\Models\CacheModel\UserCoupon;
use App\Models\CacheModel\ZlCouponAttr;
use App\Models\CacheModel\ZlcrAstr;
use App\Models\CacheModel\ZlcrAstrMessage;
use App\Models\CacheModel\ZlcrAstrNotAnswerQuestion;
use App\Models\CacheModel\ZlcrCustomReportGoods;
use App\Models\CacheModel\ZlcrCustomReportQuestion;
use App\Models\CacheModel\ZlcrCustomReportQuestionComment;
use App\Models\Api\MessageCenter;
use App\Models\Api\User;
use Exception;
use GuzzleHttp\Exception\GuzzleException;
use Db;
use Log;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

class CustomReportJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $jobData;

    /**
     * Create a new job instance.
     *
     * @param array $jobData
     */
    public function __construct(array $jobData)
    {
        $this->jobData = $jobData;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function received()
    {
      $jobData = $this->jobData;
      //        $jobData = [
//            'id' =>id 问题id,
//            'push_switch'=> 推送开关
//        ];
        $host = Util::getEcsIp();
        $startTime = date('Y-m-d H:i:s');
        $logInfo = "定制报告两小时未接单失效 开始:{$startTime} host:{$host} id:{$jobData['id']}";

        $now_time = time();
        try
        {
            $questionModel = new ZlcrCustomReportQuestion();
            //获取当前问题信息
            $question = $questionModel->getInfoById($jobData['id']);
            //若当前问题是未接单的状态则处理为订单派发超时失效       1=>问题待审核 2=>问题待接单
            if (in_array($question['status'], [1, 2], false))
            {
                //从接单队列和排行队列中去除此数据
                $delNum = $questionModel->CustomReportQueueDel($question['id']);
                if ($delNum || (isset($jobData['check_data']) && $jobData['check_data']))
                {   // 定制报告任务池 删除当前任务成功 或者为再次验证队列
                    // 订单退款
                    $OrderModel = new \app\common\cachemodel\Orders();
                    $orders = $OrderModel->getInfoById($question['order_num']);
                    $res = $OrderModel->refund($question['uid'], $orders, $orders['total_amount']);
                    if ($res['status'])
                    {
                        //若下单时间为当天晚上十点之前需还原库存数量
                        if (!empty($question['pay_time']) && date('G', $question['pay_time']) < 22)
                        {
                            //库存还原
                            (new ZlcrCustomReportGoods())->resetGoodsIndexNum();
                        }
                        //判断是否已经接单，没有接单则需要处理为订单派发超时失效
                        $questionModel->updateData($question['uid'], $question['id'], ['status' => 11, 'invalid_time' => time()]);
                        if ($jobData['push_switch'])
                        {
                            // 消息中心添加信息
                            $messageData = [
                                'status' => 0,
                                'is_read' => 0,
                                'range' => $question['uid'],
                                'type' => 2,
                                'reid' => 0,
                                'cid' => 4,//
                                'title' => '订单失效',
                                'content' => '您的定制报告订单号' . $question['order_num'] . '因派发超时已经取消，订单失效，款项将在7个工作日内原路返回，具体以支付渠道为准，敬请谅解',// 消息中心跳转地址
                                'link' => "custom_report_result_info?id={$jobData['id']}}type=3&need_auth=1",
                                'target' => 'local',
                                'create_time' => $now_time
                            ];
                            (new MessageCenter())->pushMessage($question['uid'], $messageData);
                            $pushData = ['action' => 'custom_report_result_info', 'pid' => $jobData['id'], 'type' => 3];
                            // PUSH推送报告首页
                            $pushRes = (new Push())->pushUserMsg($question['uid'], '您的定制报告订单号' . $question['order_num'] . '因派发超时已经取消，订单失效，款项将在7个工作日内原路返回，具体以支付渠道为准，敬请谅解', $pushData);
                            if (!$pushRes['success'])
                            {
                                $logInfo .= ' error: 退款完成,推送失败 message:' . $pushRes['message'];
                            }
                        }
                    } else
                    {   // 退款失败 => 发送钉钉消息
                        Log::write('定制报告ID【' . $jobData['id'] . '】退款失败', 'error', true);
                    }
                } else
                {  // 任务池删除任务失败 延迟1分钟再进行
                    //重新添加当前队列进队列池 延迟60秒执行，
                    //这里不使用延迟方法 $job->release();因为要向队列中新增参数标示任务是再次验证处理
                    // 如任务还是待接单状态，但是问题池中删除数还是为0的情况下可认定缓存异常对报告进行取消操作
                    $jobData['check_data'] = true;
                    $queueConfig = config('queue');
                    $queue_task = $queueConfig['custom_report_received_task'];
                    $queue_queue = $queueConfig['custom_report_received_queue'];
                    queuePush($queue_task, $jobData, $queue_queue, 60);
                }
            }
            $job->delete();
        }
        catch (Exception $e)
        {
            // 本命预测失败
            $logInfo .= ' error:' . $e->getMessage() . ' file:' . $e->getFile() . ':' . $e->getLine();
        }
        $logInfo .= ' jobData:' . json_encode($jobData, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        print(date('Y-m-d H:i:s') . ' ' . $logInfo);
        Log::write($logInfo, 'log', true);
    }

    /**
     * 占星师未能在4小时内首次提交，则冻结账号，取消订单，发送占星师短信、用户短信、占星师通知、用户通知
     * @param Job $job
     * @param $jobData => [
     *      'id' =>id 问题id,
     *      'astr_id'=> 咨询师id
     *      'push_switch'=> 推送开关
     *  ]
     * @throws GuzzleException
     */
    public function answer4(Job $job, $jobData): void
    {
        $jobData['astr_id'] = (int)$jobData['astr_id'];
        $jobAttempts = $job->attempts();
        if ($jobAttempts > 1)
        {
            $job->delete();
        }

        $host = Util::getEcsIp();
        $startTime = date('Y-m-d H:i:s');
        $logInfo = "报告4小时内是否首次提交检测 开始:{$startTime} host:{$host} id:{$jobData['id']}";
        $time = time();

        try
        {
            $questionModel = new ZlcrCustomReportQuestion();
            //获取当前问题信息，判断是否已经完成回答，没有则需要处理为失效
            $question = $questionModel->getInfoById($jobData['id']);
            //若当前问题是未接单的状态并且是同一个占星师则处理为占星师超时未完成失效 3=>问题待解答 4=>解答待审核 13=>待解答（回答审核未通过）
            if ((int)$question['status'] === 3 && $jobData['astr_id'] === (int)$question['astr_id']) // 如果状态还是3说明并没有完成首次提交
            {
                $questionModel->updateData($question['uid'], $question['id'], [
                    'status' => 2,
                    'astr_receiving_time' => 0,
                    'astr_id' => 0
                ]); // 弃答
                // 获取超时未回答次数
                $notAnswerQuestionNum = Db::table('wechat_backup_07_18_14_43_00.zlcr_astr_not_answer_question')->where(['astr_id' => $jobData['astr_id'], 'type' => 2])->count();
                (new ZlcrAstrNotAnswerQuestion())->notAnswerQuestionAdd([
                    'astr_id' => $jobData['astr_id'],
                    'qid' => $jobData['id'],
                    'type' => 2,
                    'remark' => '接单报告4小时内未首次提交'
                ]); // 添加弃答记录
                $notAnswerQuestionNum = $notAnswerQuestionNum + 1;
                $astrModel = new ZlcrAstr();
                $pauseTime = 0;
                if ($notAnswerQuestionNum >= 3)
                { // 超时未回答次数达到3次或以上
                    // 占星师账号冻结
                    $pauseTime = $time + 86400 * 3;
                    // (new ZlcrAstr())->UpdateData($jobData['astr_id'], ['id' => $jobData['astr_id']], ['pause_time' => $pauseTime]);
                    // 占星师站内信
                    (new ZlcrAstrMessage())->add($jobData['astr_id'], [
                        'status' => 0,
                        'is_read' => 0,
                        'astr_id' => $jobData['astr_id'],
                        'type' => 9, // 占星师违规消息
                        'title' => '账号冻结通知',
                        'content' => '由于您已经' . $notAnswerQuestionNum . '次提交超时，无法完成服务流程，您的账号做冻结3天处理，解封或有异议请添加客服微信xzns01咨询。',
                        'target' => '',
                        'link' => '',
                        'create_time' => $time
                    ]);
                    // 占星师短信通知
                    $tel = $astrModel->getInfoById($jobData['astr_id'], ['tel']);
                    Util::sendYxSms([$tel['tel']], $extend = '', 37770, ['num' => $notAnswerQuestionNum, 'time' => '3天']); // 发送冻结短信
                }
                // 更新占星师 能力值 行为 并 冻结账号（判断$pauseTime>0）
                $astrModel->changeAstr($jobData['astr_id'], $jobData['id'], -10, 3, $pauseTime); // 提交超时 更新占星师能力值

                $astrModel->underwayTaskDel($jobData['astr_id'], [$jobData['id']]); // 待解答问题删除
                // 将问题抛回问题池
                $questionModel->CustomReportQueueAdd($jobData['id'], 2);
            }
            $job->delete();
        }
        catch (Exception $e)
        {
            // 定制报告失败
            $logInfo .= ' error:' . $e->getMessage() . ' file:' . $e->getFile() . ':' . $e->getLine();
        }
        $logInfo .= ' jobData:' . \GuzzleHttp\json_encode($jobData, JSON_UNESCAPED_UNICODE);
        print(date('Y-m-d H:i:s') . ' ' . $logInfo);
        Log::write($logInfo, 'log', true);
    }

    /**
     * 若因审核原因造成6小时内未能提交至用户，也冻结账号
     * @param Job $job
     * @param $jobData
     * @throws GuzzleException
     */
    public function answer6(Job $job, $jobData): void
    {
//        $jobData = [
//            'id' =>id 问题id,
//            'astr_id'=> 咨询师id
//            'push_switch'=> 推送开关
//        ];

        $jobAttempts = $job->attempts();
        if ($jobAttempts > 1)
        {
            $job->delete();
        }

        $host = Util::getEcsIp();
        $startTime = date('Y-m-d H:i:s');
        $logInfo = "定制报告6小时内未能提交至用户 开始:{$startTime} host:{$host} id:{$jobData['id']}";

        $now_time = time();
        try
        {
            $questionModel = new ZlcrCustomReportQuestion();
            //获取当前问题信息，判断是否已经完成回答，没有则需要处理为失效
            $question = $questionModel->getInfoById($jobData['id']);
            //若当前问题是未接单的状态并且是同一个占星师则处理为占星师超时未完成失效       3=>问题待解答 4=>解答待审核 13=>待解答（回答审核未通过）
            if (in_array($question['status'], [2, 3, 4, 13], false))
            {
                // 订单退款
                $OrderModel = new \app\common\cachemodel\Orders();
                $orders = $OrderModel->getInfoById($question['order_num']);
                $res = $OrderModel->refund($question['uid'], $orders, $orders['total_amount']);
                if ($res['status'])
                {
                    // 获取当前占星师问题超时次数
                    $num = $questionModel->where(['astr_id' => $question['astr_id'], 'status' => 12])->count();
                    $num = $num + 1;
                    if ($num >= 3)
                    {
                        $day = 15;
                    } elseif ($num === 2)
                    {
                        $day = 7;
                    } else
                    {
                        $day = 3;
                    }
                    $pauseTime = $now_time + 86400 * $day;
                    $questionModel->updateData($question['uid'], $question['id'], ['status' => 12, 'invalid_time' => time()]);
                    //获取当前占星师的openid
                    // $openId = (new ZlcrWechatSubscribe())->where(['astr_id' => $question['astr_id']])->column('openid');
                    // if ($openId)
                    // {
                    //     //给占星师发送公众号模板消息
                    //     (new WechatServiceAccountManage())->sendTemplateMsg(current($openId));
                    // }
                    //赠送月运免费券
                    $this->giveUserCoupon($question['uid']);
                    // 占星师账号冻结
                    //(new ZlcrAstr())->UpdateData($question['astr_id'], ['id' => $question['astr_id']], ['pause_time' => $pauseTime]);
                    // 更新占星师 能力值 行为 并且冻结账号
                    (new ZlcrAstr())->changeAstr($jobData['astr_id'], $jobData['id'], -20, 4, $pauseTime); // 问题超时 更新占星师能力值
                    // 占星师站内信
                    (new ZlcrAstrMessage())->add($question['astr_id'], [
                        'status' => 0,
                        'is_read' => 0,
                        'astr_id' => $question['astr_id'],
                        'type' => 9, // 占星师违规消息
                        'title' => '账号冻结通知',
                        'content' => '由于编号为' . $jobData['id'] . '的定制报告超时回复，无法完成服务流程，您的账号做冻结' . $day . '天处理，解封或有异议请添加客服微信xzns01详细咨询',
                        'target' => '',
                        'link' => '',
                        'create_time' => $now_time
                    ]);
                    // 占星师短信通知
                    $astrModel = new ZlcrAstr();
                    $tel = $astrModel->getInfoById($question['astr_id'], ['tel']);
                    Util::sendYxSms([$tel['tel']], $extend = '', 37766, ['question_num' => $question['id'], 'time' => $day . '天']);
                    $astrModel->underwayTaskDel($question['astr_id'], [$jobData['id']]); // 待解答问题删除
                    // 用户短信通知
                    $userIndo = (new User())->getUserinfo(['id' => $question['uid']]);
                    Util::sendYxSms([$userIndo['tel']], $extend = '', 30173, ['' => '']);
                    // 消息中心添加信息
                    $messageData = [
                        'status' => 0,
                        'is_read' => 0,
                        'range' => $question['uid'],
                        'type' => 2,
                        'reid' => 0,
                        'cid' => 4,
                        'title' => '定制报告已失效',
                        'content' => '⾮常抱歉，您的定制报告订单号' . $question['order_num'] . '因占星师个⼈原因已经取消，订单失效，款项7个⼯作⽇内原路返回，赔偿您⼀个⽉⽉运免费卷已经发放⾄卡劵中⼼',// 消息中心跳转地址
                        'link' => "custom_report_result_info?id={$jobData['id']}}type=3&need_auth=1",
                        'target' => 'local',
                        'create_time' => $now_time
                    ];
                    (new MessageCenter())->pushMessage($question['uid'], $messageData);
                    if ($jobData['push_switch'])
                    {
                        $pushData = ['action' => 'custom_report_result_info', 'pid' => $jobData['id'], 'type' => 3];
                        // PUSH推送报告首页
                        $pushRes = (new Push())->pushUserMsg($question['uid'], '⾮常抱歉，您的定制报告订单号' . $question['order_num'] . '因占星师个⼈原因已经取消，订单失效，款项7个⼯作⽇内原路返回，赔偿您⼀个⽉⽉运免费卷已经发放⾄卡劵中⼼', $pushData);
                        if (!$pushRes['success'])
                        {
                            $logInfo .= ' error: 订单取消完成,推送失败 message:' . $pushRes['message'];
                        }
                    }
                } else
                {   // 退款失败 => 发送钉钉消息
                    Log::write('定制报告ID【' . $jobData['id'] . '】退款失败', 'error', true);
                }
            }
            $job->delete();
        }
        catch (Exception $e)
        {
            // 本命预测失败
            $logInfo .= ' error:' . $e->getMessage() . ' file:' . $e->getFile() . ':' . $e->getLine();
        }
        $logInfo .= ' jobData:' . json_encode($jobData, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        print(date('Y-m-d H:i:s') . ' ' . $logInfo);
        Log::write($logInfo, 'log', true);
    }

    /**
     * 定制报告 指定占星师 12小时后是否完成  未完成则退款
     * 8-18点下单 则 下单时间+12小时   否则 次日8点+12小时
     * @param Job $job
     * @param $jobData
     * @return void
     * @throws GuzzleException
     */
    public function reportSucCheck(Job $job, $jobData): void
    {
//        $jobData = [
//            'id' =>id 问题id,
//            'astr_id'=> 咨询师id
//            'push_switch'=> 推送开关
//        ];
        $jobAttempts = $job->attempts();
        if ($jobAttempts > 1)
        {
            $job->delete();
        }
        $host = Util::getEcsIp();
        $startTime = date('Y-m-d H:i:s');
        $logInfo = "定制报告 指定咨询师 12小时内未能提交至用户 开始:{$startTime} host:{$host} id:{$jobData['id']}";

        $now_time = time();
        try
        {
            $questionModel = new ZlcrCustomReportQuestion();
            //获取当前问题信息，判断是否已经完成回答，没有则需要处理为失效
            $question = $questionModel->getInfoById($jobData['id']);
            //若当前问题是未接单的状态并且是同一个占星师则处理为占星师超时未完成失效       3=>问题待解答 4=>解答待审核 13=>待解答（回答审核未通过）
            if (in_array($question['status'], [2, 3, 4, 13], false))
            {
                // 订单退款
                $OrderModel = new \app\common\cachemodel\Orders();
                $orders = $OrderModel->getInfoById($question['order_num']);
                $res = $OrderModel->refund($question['uid'], $orders, $orders['total_amount']);
                if ($res['status'])
                {
                    // 获取当前占星师问题超时次数
                    $num = $questionModel->where(['astr_id' => $question['astr_id'], 'status' => 12])->count();
                    $num = $num + 1;
                    if ($num >= 3)
                    {
                        $day = 15;
                    } elseif ($num === 2)
                    {
                        $day = 7;
                    } else
                    {
                        $day = 3;
                    }
                    $pauseTime = $now_time + 86400 * $day;
                    $questionModel->updateData($question['uid'], $question['id'], ['status' => 12, 'invalid_time' => time()]);
                    //获取当前占星师的openid
                    // $openId = (new ZlcrWechatSubscribe())->where(['astr_id' => $question['astr_id']])->column('openid');
                    // if ($openId)
                    // {
                    //     //给占星师发送公众号模板消息
                    //     (new WechatServiceAccountManage())->sendTemplateMsg(current($openId));
                    // }
                    //赠送月运免费券
                    $this->giveUserCoupon($question['uid']);
                    // 占星师账号冻结
                    //(new ZlcrAstr())->UpdateData($question['astr_id'], ['id' => $question['astr_id']], ['pause_time' => $pauseTime]);
                    // 更新占星师 能力值 行为 并且冻结账号
                    (new ZlcrAstr())->changeAstr($jobData['astr_id'], $jobData['id'], -20, 4, $pauseTime); // 问题超时 更新占星师能力值
                    // 占星师站内信
                    (new ZlcrAstrMessage())->add($question['astr_id'], [
                        'status' => 0,
                        'is_read' => 0,
                        'astr_id' => $question['astr_id'],
                        'type' => 9, // 占星师违规消息
                        'title' => '账号冻结通知',
                        'content' => '由于编号为' . $jobData['id'] . '的定制报告超时回复，无法完成服务流程，您的账号做冻结' . $day . '天处理，解封或有异议请添加客服微信xzns01详细咨询',
                        'target' => '',
                        'link' => '',
                        'create_time' => $now_time
                    ]);
                    // 占星师短信通知
                    $astrModel = new ZlcrAstr();
                    $tel = $astrModel->getInfoById($question['astr_id'], ['tel']);
                    Util::sendYxSms([$tel['tel']], $extend = '', 37766, ['question_num' => $question['id'], 'time' => $day . '天']);
                    $astrModel->underwayTaskDel($question['astr_id'], [$jobData['id']]); // 待解答问题删除
                    // 用户短信通知
                    $userIndo = (new User())->getUserinfo(['id' => $question['uid']]);
                    Util::sendYxSms([$userIndo['tel']], $extend = '', 30173, ['' => '']);
                    // 消息中心添加信息
                    $messageData = [
                        'status' => 0,
                        'is_read' => 0,
                        'range' => $question['uid'],
                        'type' => 2,
                        'reid' => 0,
                        'cid' => 4,
                        'title' => '定制报告已失效',
                        'content' => '⾮常抱歉，您的定制报告订单号' . $question['order_num'] . '因占星师个⼈原因已经取消，订单失效，款项7个⼯作⽇内原路返回，赔偿您⼀个⽉⽉运免费卷已经发放⾄卡劵中⼼',// 消息中心跳转地址
                        'link' => "custom_report_result_info?id={$jobData['id']}}type=3&need_auth=1",
                        'target' => 'local',
                        'create_time' => $now_time
                    ];
                    (new MessageCenter())->pushMessage($question['uid'], $messageData);
                    if ($jobData['push_switch'])
                    {
                        $pushData = ['action' => 'custom_report_result_info', 'pid' => $jobData['id'], 'type' => 3];
                        // PUSH推送报告首页
                        $pushRes = (new Push())->pushUserMsg($question['uid'], '⾮常抱歉，您的定制报告订单号' . $question['order_num'] . '因占星师个⼈原因已经取消，订单失效，款项7个⼯作⽇内原路返回，赔偿您⼀个⽉⽉运免费卷已经发放⾄卡劵中⼼', $pushData);
                        if (!$pushRes['success'])
                        {
                            $logInfo .= ' error: 订单取消完成,推送失败 message:' . $pushRes['message'];
                        }
                    }
                } else
                {   // 退款失败 => 发送钉钉消息
                    Log::write('定制报告ID【' . $jobData['id'] . '】退款失败', 'error', true);
                }
            }
            $job->delete();
        }
        catch (Exception $e)
        {
            // 本命预测失败
            $logInfo .= ' error:' . $e->getMessage() . ' file:' . $e->getFile() . ':' . $e->getLine();
        }
        $logInfo .= ' jobData:' . json_encode($jobData, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        print(date('Y-m-d H:i:s') . ' ' . $logInfo);
        Log::write($logInfo, 'log', true);
    }

    /**
     * 报告完成后三天未完成评论则自动评论
     * @param Job $job
     * @param $jobData
     * @throws GuzzleException
     */
    public function comment(Job $job, $jobData): void
    {
        $jobAttempts = $job->attempts();
        if ($jobAttempts > 1)
        {
            $job->delete();
        }

        $host = Util::getEcsIp();
        $startTime = date('Y-m-d H:i:s');
        $logInfo = "定制报告自动评论 开始:{$startTime} host:{$host} id:{$jobData['id']}";

        $now_time = time();
        try
        {
            $questionModel = new ZlcrCustomReportQuestion();
            //获取当前问题信息，判断是否已经评论，没有则需要处理为失效
            $question = $questionModel->getInfoById($jobData['id']);
            $question['astr_id'] = (int)$question['astr_id'];
            //若当前问题是未接单的状态则自动评论并修改问题状态为已完成评价       5=>已完成待评价
            if ($question['status'] == 5)
            {
                $inserData = [
                    'qid' => $question['id'],
                    'level' => 3,
                    'tid' => 55,//平淡无味
                    'status' => 2,
                    'comment' => '',
                    'astr_id' => $question['astr_id'],
                    'comment_type' => 2,
                    'aid' => 0,
                    'create_time' => time(),
                    'check_time' => 0
                ];
                (new ZlcrCustomReportQuestionComment())->saveData($inserData);
                $questionModel->updateData($question['uid'], $question['id'], ['status' => 7]);
                // 更新占星师好评率
                $rating = (new ZlcrCustomReportQuestionComment())->getRating($question['astr_id']);
                (new ZlcrAstr())->UpdateData($question['astr_id'], ['id' => $question['astr_id']], ['rating' => (float)$rating, 'update_time' => $inserData['create_time']]);
            }
            $job->delete();
        }
        catch (Exception $e)
        {
            // 本命预测失败
            $logInfo .= ' error:' . $e->getMessage() . ' file:' . $e->getFile() . ':' . $e->getLine();
        }
        $logInfo .= ' jobData:' . json_encode($jobData, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        print(date('Y-m-d H:i:s') . ' ' . $logInfo);
        Log::write($logInfo, 'log', true);
    }

    /**
     * 赠送用户优惠券
     * @param $uid
     * @return void
     * @throws Exception
     */
    public function giveUserCoupon($uid)
    {
        $cid = 65;//优惠券id 月运免费券
        $endTime = 0;//优惠券最终使用期限为永久
        // 获取赠送的优惠券信息
        $coupon = (new ZlCouponAttr())->getInfoById($cid);
        // 添加赠送记录
        $award_infos = [
            'status' => 1,
            'type' => 3,
            'auid' => $uid,
            'agid' => $cid,
            'admin_id' => 0,
            'create_time' => time(),
            'desc' => '因占星师回答超时的赔偿'
        ];
        (new AwardGoods())->saveData($award_infos);

        $time = time();

        $price = $coupon['type'] == 4 ? mt_rand($coupon['rand_min'], $coupon['rand_max']) : 0;
        $cData[] = [
            'uid' => $uid,
            'c_id' => $coupon['id'],
            'ur_id' => 62,
            'start_time' => $time,
            'end_time' => $endTime,
            'give_time' => $time,
            'status' => 0,
            'price' => $price,
            'is_give' => 0,
            'create_time' => $time,
            'update_time' => 0
        ];
        (new UserCoupon())->add($uid, $cData);
    }
}